﻿/*//平台、设备和操作系统
var system ={
win : false,
mac : false,
xll : false
};
//检测平台
var p = navigator.platform;
system.win = p.indexOf("Win") == 0;
system.mac = p.indexOf("Mac") == 0;
system.x11 = (p == "X11") || (p.indexOf("Linux") == 0);
//跳转语句，如果是电脑访问就自动跳转到computer.html页面
if(system.win||system.mac||system.xll){
	window.location.href="computer.html";
}else{
//手机网站
}*/

var availWidth = window.screen.width;//屏幕可用工作区宽度
if(isBlank(availWidth)) availWidth = 320;

var baseRoot = "http://121.197.1.194";//http://192.168.1.100:8080
var baseUrl = baseRoot+"/demo/";//"http://"+window.location.host ,$("base").attr("href")
var wechat_id = "";
var userId = "";
//var baseRoot = "http://112.124.41.175";
//var baseUrl = baseRoot+"/maicai/";//$("base").attr("href")
//var wechat_id = "o6NmcjnHjI4dHt4ZAbl59zjaw_fI";

var detail_id="";
var cartId = 0;
var userStatus = 0;

var whichPageAfterLogin = "";//记录登录之后跳转的页面

var orders = Array();//存放购物车、订单的水果对应的ID（除土特团之外的才，一样菜只能买一道）
var tutetuans = Array();//存放购物车、订单的水果对应的ID（只对应土特团的菜，因为这个有数量）fruits
var fruits = Array();
//var suixinpeis = Array();//存放随心配的购物车、订单的水果对应的ID（搭配特殊）
/**
 * 是否为空
 */
function isBlank(a) {
    if (a == undefined || a == null || a == "null" || a == "undefined" || a == "") {
        return true;
    }
    return false;
}

//计算购物车物品的数量（即suixinpeis、fruits存放的有效商品ID）
function _count(){
	var count = 0;
	for(var i in fruits){
		if(fruits[i] != -1)
			count++;
	}
//	for(var i in suixinpeis){
//		if(suixinpeis[i] != -1)
//			count++;
//	}
	return count;
}

/*
 * 四则运算精度修正函数 m 数值1(number) n 数值2(number) op 操作符(string)
 */
function fixMath(m, n, op) {
	var a = (m + "");
	var b = (n + "");
	var x = 1;
	var y = 1;
	var c = 1;
	if (a.indexOf(".") > 0) {
		x = Math.pow(10, a.length - a.indexOf(".") - 1);
	}
	if (b.indexOf(".") > 0) {
		y = Math.pow(10, b.length - b.indexOf(".") - 1);
	}
	switch (op) {
	case '+':
	case '-':
		c = Math.max(x, y);
		m = Math.round(m * c);
		n = Math.round(n * c);
		break;
	case '*':
		c = x * y
		m = Math.round(m * x);
		n = Math.round(n * y);
		break;
	case '/':
		c = Math.max(x, y);
		m = Math.round(m * c);
		n = Math.round(n * c);
		c = 1;
		break;
	}
	return eval("(" + m + op + n + ")/" + c);
}
function goTo(page) {
	showLoading();
	$.mobile.changePage(page, {
		transition:"flip"
	});
}
function goBack() {
	$.mobile.back();
}

function showLoading() {
	$.mobile.loadingMessageTextVisible = true;
	$.mobile.showPageLoadingMsg("a", "加载中...");
}

function hideLoading() {
	$.mobile.hidePageLoadingMsg();
}

function showMyAlert(text) {
	$.mobile.loadingMessageTextVisible = true;
	$.mobile.showPageLoadingMsg("a", text, true);
}
function myAlert(text) {
	showMyAlert(text);
	setTimeout(hideLoading, 2000);
}

function errpic(thepic) { 
	thepic.src = "img/no_pic.png";
}


//底部部点击事件（鲜果切、随心配、免洗果、组合餐）
function clickTypes(num){
	var pageId = "pageA";
	var url = baseUrl+"student/studentAction_studentList.action?num="+num;
	if(num == 0){
		pageId = "pageA";
	}else if(num ==3 ){
		pageId = "pageB";
	}else if(num == 2){
		pageId = "pageC";
	}else if(num == 1){
		pageId = "pageD";
	}

		url = baseUrl+"student/studentAction_studentList.action?num="+num;
		//url = 'index.json';
		$.ajax({
			url: url,
			success: function(data){
				console.log(data);
				var data 		= eval("("+data+")");
				var common 		= data.common;
				var special		= data.special;
				var recommend	= data.recommend;
				var divs		= '';
				
				for(var r in recommend){
					var div = '<div id="i" class="special" name="'+ recommend[r].productId+'"><div class="title">'+
						'<span>今日推荐：</span><p>' + recommend[r].productName +
						'</p><div>'+recommend[r].subheading+'</div>'+
						'</div><img onerror=errpic(this) class="item-image" src="'+baseUrl+ recommend[r].productImage +'" />' +
						'<span name="'+ recommend[r].productId+'" class="detail">详情<img style="width:8px;margin-left: 5px;margin-top:-5px;" src="img/greentri@2x.png"/></span>' +
						'<span class="price" style="color:green;">¥'+ recommend[r].pricePri +'</span>' +
						isShowPriceAccount(recommend[r].priceAccount)+
						'<span class="weight"><img style="width: 15px;margin-right:5px;margin-top:-5px;" src="img/shuiguojiejie.png"/>'+ recommend[r].components +'</span></div>';
					divs+=div;
				}
				for(var s in special){
					var div = '<div id="i" class="special" name="'+ special[s].productId+'"><div class="title">'+
						'<span>今日特价：</span><p>' + special[s].productName +
						'</p><div>'+special[s].subheading+'</div>'+
						'</div><img  onerror=errpic(this) class="item-image" src="'+baseUrl+ special[s].productImage +'" />' +
						'<span name="'+ special[s].productId+'" class="detail">详情<img style="width:8px;margin-left: 5px;margin-top:-5px;" src="img/greentri@2x.png"/></span>' +
						'<span class="price" style="color:green;">¥'+ special[s].pricePri +'</span>' +
						isShowPriceAccount(special[s].priceAccount)+
						'<span class="weight"><img style="width: 15px;margin-right:5px" src="img/bow@2x.png"/>'+ special[s].components +'</span></div>';
					divs+=div;
				}		
				for(var c in common){
					var div = '<div id="i" class="single" name="'+ common[c].productId+'"><div class="title">'+
						common[c].productName +
						'</div><img onerror=errpic(this) class="item-image" src="'+baseUrl+ common[c].productImage +'" />' +
						'<span class="price" style="color:green;">¥'+ common[c].pricePri +'</span>' +
						isShowPriceAccount(common[c].priceAccount)+
						'<span class="weight"><img style="width: 15px;margin-right:5px;margin-top:-5px;" src="img/bow@2x.png"/>'+ common[c].components +'</span>'+
						'<div name="'+ common[c].productId+'" class="detail">详情<img style="width:8px;margin-left: 5px;margin-top:-5px;" src="img/greentri@2x.png"/></div></div>';
					divs+=div;
				}
				var page = $("#"+pageId);
				page.find(".items div").remove();
				page.find(".items").append(divs);
				
				var count = _count();
				$(".cart #number").text(count);
				if(count > 0){
					$(".cart").show();
				}
				else {
					$(".cart").hide();
				}
				//setShadow();
			//	itemClick();
			}
		});			

}

function isShowPriceAccount(pri){
	if(parseFloat(pri)>0){
		return '<del class="price">¥'+ pri +'</del>';
	}else{
		return '';
	}
}

//设置是否要显示选中的“阴影”效果
function setShadow(){
	$(".home-shadow").remove();
	$("#home-items div#i").each(function(i, el){
		var heightGap = 30;
		var width = (availWidth-30)/2, height = 110;
		var id = $(this).parent().attr("name");
		if($(el).hasClass("special") || $(el).hasClass("recommend")){
			heightGap = 80;
			width = (availWidth*0.95-1), height = 210;
		}
		
		var productId = $(el).attr("name");
		//if($(".types .active").attr("name") == "3"){
		if($.inArray(productId,fruits)!=-1){
			if(fruits[productId] == productId){
				var img = $(el).find(".item-image");
				$(el).append(
					'<div id="shadow'+ $(el).attr("name") +'" class="home-shadow"style="position:absolute; '+
					'width: '+ width +'px; '+
					'height: '+ (height-heightGap)+'px;'+
					'left: '+ img.offset().left +'px; '+
					'top: '+ img.offset().top +'px;'+ 
					'padding-top: '+heightGap+'px">' +
					'<div><img src="'+baseUrl+'img/check.png"/>&nbsp;&nbsp;已选</div></div>'
				);
			}
		}
/*		else {
			if(orders[$(el).attr("name")] == $(el).attr("name")){
				var img = $(el).find(".item-image");
				$(el).append(
					'<div id="shadow'+ $(el).attr("name") +'" class="home-shadow"style="position:absolute; '+
					'width: '+ img.offset().width +'px; '+
					'height: '+ (img.offset().height-heightGap)+'px;'+
					'left: '+ img.offset().left +'px; '+
					'top: '+ img.offset().top +'px;'+ 
					'padding-top: '+heightGap+'px">' +
					'<div><img src="'+baseUrl+'img/check.png"/>&nbsp;&nbsp;已选</div></div>'
				);
			}
		}*/
	});
	
	var count = _count();
	$(".cart #number").text(count);
	if(count > 0){
		$(".cart").show();
	}
	else {
		$(".cart").hide();
	}
}

//去掉或显示阴影效果（点击图片的时候）
function shadow(){
	var self = this;
	var heightGap = 30;
	var id = $(this).parent().attr("name");
	if($(this).parent().hasClass("special") || $(this).parent().hasClass("recommend")){
		heightGap = 80;
	}
	
	if($(".types .active").attr("name") == 3){
		if(fruits[id] > 0){
			fruits[id] = -1;
			$("div #shadow"+id).remove();
		}
		else {
			fruits[id] = id;
			//console.log(tutetuans);
			$(self).parent().append(
				'<div id="shadow'+ id +'" class="home-shadow"style="position:absolute; '+
				'width: '+ self.scrollWidth+'px; '+
				'height: '+ (self.scrollHeight-heightGap)+'px;'+
				'left: '+ self.x+'px; '+
				'top: '+ self.y +'px;'+ 
				'padding-top: '+heightGap+'px">' +
				'<div><img src="img/check.png"/>&nbsp;&nbsp;已选</div></div>'
			);
		}
	
	}
	else {
		if(fruits[id] > 0){//之前加入购物车了
			fruits[id] = -1;
			$("div #shadow"+id).remove();
		}
		else {
			fruits[id] = id;
			$(self).parent().append(
				'<div id="shadow'+ id +'" class="home-shadow"style="position:absolute; '+
				'width: '+ self.scrollWidth+'px; '+
				'height: '+ (self.scrollHeight-heightGap)+'px;'+
				'left: '+ self.x+'px; '+
				'top: '+ self.y +'px;'+ 
				'padding-top: '+heightGap+'px">' +
				'<div><img src="img/check.png"/>&nbsp;&nbsp;已选</div></div>'
			);
		}
	}
	
	console.log("fruits:"+fruits);
	
	var count = _count();
//	alert(count)
	$(".cart #number").text(count);
	if(count > 0){
		$(".cart").show();
	}
	else {
		$(".cart").hide();
	}
}

$(document).on("click", "#home-items .home-shadow", shadow);//列表图片上的阴影选中效果图片的点击事件
$(document).on("click", "#home-items .item-image", shadow);//列表图片的点击事件

$(document).on("click", "div.cart", function(){
//	alert("userStatus:"+userStatus)
//	userStatus = 1;
	whichPageAfterLogin = "";//cart.html 去除登录之后去看订单历史的标志
	if(userStatus == 1){
		goTo('cart.html');
	}else {
		goTo('login.html');
	}
});

//悬浮的购物车图标，点击事件
//$("div.cart").click(function(){
	//$(".cart").hide();
	//alert("goto cart");
	//cartDetailGet();
//	history.push({
//		url: window.location,
//		page: 'cart-items',
//		id: '#cart-items',
//		header: '#cart-header',
//		time: new Date()
//	});
	
//	$("#home-header").hide();
//	$("#home-items").hide();
//	$("#detail-header").hide();
//	$("#detail-item").hide();
//	$("#cart-header").show();
//	$("#cart-items").show();
//});

/**
 * Get请求购物车详情
 */
function cartDetailGet(){
	$("#in-cart-items div").remove();
	$("#in-tuan-items div").remove();
	//$("#amount_1").hide();
	$("#amount_2").hide();
	//var wechat_id = $("#wechat_id").val();
	var url ;//= baseUrl+'ajax/cartDetailGet/'+wechat_id;
	url =baseUrl+"student/studentAction_addToCartOrBrowse.action?;"
	//url = 'cartDetailGet.json';
	//console.log(tutetuans);
	//tutetuans=[14,18];
	var fruitServer = Array();
	for(var i in fruits){
		if(fruits[i]>0) fruitServer.push(fruits[i]);
	}
	//fruits = temp;
	
	if(_count()<1) {
		goTo('index.html');
		return;
	}
		
	var counts = Array();
	for(var i in fruitServer){
		counts.push(1);
	}
	
	if(isBlank(cartId)) cartId = 0;
	
	$.ajax({
		url: url,
		data: { userId:userId,cartId:cartId,fruits: fruitServer,counts:counts},
		success: function(data){
			console.log(data);
			var data = eval("("+data+")");
			//if(data=="null") goTo('index.html');
			// 计算图特团
			cartId = data.cartId;
			var fruit = data.cart;
			var sxp = data.sxp;
			var user = data.user;
			console.log(user)
			var cartItems = "";
			//var total = 0;
			if(fruit){
				//prices = Array();
				for(var i in fruit){
					var item = '<div class="item" name="tutetuan">'
						+ '<input id="priceofid'+fruit[i].productId+'" type="hidden" value="'+ fruit[i].price +'"/>'
						+ '<img onerror=errpic(this) src="'+ baseUrl + fruit[i].productImage +'" />'
						+ '<div class="info" name="tutetuan">'
						+ '<span style="font-size:14px;padding-top: 20px;">' + fruit[i].productName +'&nbsp;&nbsp;'+fruit[i].price+'元/'+fruit[i].standard+'</span>'
						//+ '<span style="font-size:14px;">'+fruit[i].price+'元/'+fruit[i].standard+'</span>'
						//+ '<span class="name" style="padding:12px 5px 0px 0">'+ tuan[i].name+'&nbsp;&nbsp;<p style="float:right;padding:0;margin:0;padding-top:5px;">'+tuan[i].time+'配送</p></span>'
						//+ '<span class="price" style="margin:0;padding:0">'+ tuan[i].price +'元 '+ tuan[i].number +'人起团</span>'
						+ '<a id="'+fruit[i].productId+'" name="'+fruit[i].price+'" class="item-remove delete" style="margin-top:5px">删除</a>'
						+ '<span style="width:120px;display:inline-block;margin-top:5px;"><button name="numberofid'+fruit[i].productId+'" class="minus">-</button>&nbsp;&nbsp;<label style="display:inline-block" id="numberofid'+fruit[i].productId+'" style="width:20px;">1</label>&nbsp;&nbsp;<button name="numberofid'+fruit[i].productId+'"class="plus">+</button></span>'
						+ '</div>'
						+ '<div class="border"></div></div>';
					cartItems += item;
					//total += parseFloat(tuan[i].price);
					//prices.push(fruit[i].price);
				}
				$("#in-tuan-items").append(cartItems).trigger( "updatelayout" );
				//$("#amount_2").show();
			}
			cartItems = "";
			if(sxp.length>0){
				$("#suixinpei-tip").show();
				for(var i in sxp){
					var item = '<div class="item" name="suixinpei">'
						+ '<input id="priceofid'+sxp[i].productId+'" type="hidden" value="'+ sxp[i].price +'"/>'
						+ '<img onerror=errpic(this) src="'+ baseUrl + sxp[i].productImage +'" />'
						+ '<div class="info" name="tutetuan">'
						+ '<span style="font-size:14px;padding-top: 20px;">' + sxp[i].productName +'&nbsp;&nbsp;'+sxp[i].price+'元/'+sxp[i].standard+'</span>'
						+ '<a id="'+sxp[i].productId+'" name="'+sxp[i].price+'" class="item-remove delete" style="margin-top:5px">删除</a>'
						+ '<span style="width:120px;display:inline-block;margin-top:5px;"><button name="numberofid'+sxp[i].productId+'" class="minus">-</button>&nbsp;&nbsp;<label style="display:inline-block" id="numberofid'+sxp[i].productId+'" style="width:20px;">1</label>&nbsp;&nbsp;<button name="numberofid'+sxp[i].productId+'"class="plus">+</button></span>'
						+ '</div>'
						+ '<div class="border"></div></div>';
					cartItems += item;
				}
				$("#in-cart-items").append(cartItems).trigger( "updatelayout" );
				$("#amount_2").show();
			}else{
				$("#suixinpei-tip").hide();
			}			
			
			console.log('total:'+data.totalMoney);
			$("#tuan-all").text(data.totalMoney);
			
			//显示配送信息
			$("#cart-name").text(user.name);
			$("#cart-phone").text(user.phoneNumber);
			$("#cart-location").text(user.address);
			
			setDeliveryTime();
		}
	});
	//goTo("index4.html");
}

/**
 * 动态生成可选的配送时间
 * 配送规则:19为开始配送时间,整点配送，每小时配送一次,提前30分钟(含30)下单
 * 时间段为19-24点。注意：开始配送时间js要和cart.html页面的值对应
 */
function setDeliveryTime(){
	var date=new Date(); 
	var hour = date.getHours();
	if(date.getMinutes()>30){hour++;}//30分钟时也可下单
	console.log("hour:"+hour);
	hour = hour-19;//19为开始配送时间
	console.log("hour:"+hour);

	var $select = $("#delivery-time");
	var $option = $select.find("option");
	
	var index = 1; //index即是option.value,value=0是提示信息(请选择可配送时间)
	hour++;
	for(;index<=$option.length;index++){
		if(hour >= index && index<4){
			$select.find("option[value="+index+"]").attr("disabled","disabled");	
		}
	}
}

/**
 * 修改配送信息(接收人信息)
 */
function updateDeliveryInfo(){
	var phoneNumber = $("#delivery-tel").val();
	var name = $("#delivery-name").val();
	var address = $("#delivery-address").val();
	if(isBlank(phoneNumber) || isBlank(name) || isBlank(address)){
		$("#delivery-msg").text("请填写完整信息!");
		return;
	}
	if((phoneNumber.length>2 && phoneNumber.length<7) || phoneNumber.length==11 ){
	}else{
		$("#delivery-msg").text("手机号码不正确");
		return;
	}

	$("#delivery-msg").text('');
	console.log("phoneNumber:"+phoneNumber+"name:"+name+"address:"+address);
	var url = baseUrl + "student/studentAction_updateRecipientAddress.action";
	$.ajax({
		url: url,
		type: "POST",
		async: false,//同步请求
		data:{userId:userId,recipientPhone:phoneNumber,recipientName:name,recipientAddress:address},
		beforeSend:function(){
			$("#delivery-submit").addClass("ui-disabled");
		},
		success: function(data){
			var data = eval("("+data+")");
			if(data.sign==1){//修改成功
				myAlert("修改成功");
				//显示配送信息
				$("#cart-name").text(name);
				$("#cart-phone").text(phoneNumber);
				$("#cart-location").text(address);
				$("#delivery-dialog").dialog("close");
				goTo('cart.html');
			}else{//data.login == 1修改失败
				myAlert("修改失败");
			}
		},
		error: function(data){
			$("#delivery-msg").text('修改失败');
			myAlert("修改失败");
		},
		complete:function(){
			$("#delivery-submit").removeClass("ui-disabled");
		}
	});
}

//修改备注信息
function showRemark(){
	$("#cart-remark").toggle();
}

//在列表页面，点击“详情”响应事件，大块样式
$(document).on("click" ,".special span.detail", function(){

	detail_id = $(this).attr("name");
	
	var count = _count();
	$(".cart #number").text(count);
	if(count > 0){
		$(".cart").show();
	}
	else {
		$(".cart").hide();
	}
	
	goTo("detail.html");
});

//在列表页面，点击“详情”响应事件，小块样式
$(document).on("click", ".single .detail", function(){
	detail_id = $(this).attr("name");
	
	var count = _count();
	$(".cart #number").text(count);
	if(count > 0){
		$(".cart").show();
	}
	else {
		$(".cart").hide();
	}
	
	goTo("detail.html");
});

//普通列表详情页面
function itemDetailGet(id){
	var url = baseUrl + "student/studentAction_showProductDetail.action?productId="+id;
	//url = 'cut_detail.json';
	$.ajax({
		url: url,
		success: function(data){
			console.log(data);
			var data = eval("("+ data +")");
			$("#detail-header-name").text(data.productName);
			$("#detail-item-id").val(data.productId);
			var detailItem = $("#detail-item");
			//detailItem.find("#detail-1").text("价格:");
			//detailItem.find("#detail-2").text("规格:");
			//detailItem.find("#detail-3").text("成分:");
			//detailItem.find("#detail-4").text("介绍:");
			
			detailItem.find("#detail-item-img").attr("src", baseUrl + data.productImage);
			detailItem.find("#price").text(data.pricePri+"元");
			detailItem.find("#volume").text(data.standard);
			detailItem.find("#material").text(data.components);
			detailItem.find("#submaterial").text(data.productDetail);
		}
	});
	
	var count = _count();
	$(".cart #number").text(count);
	if(count > 0){
		$(".cart").show();
	}
	else {
		$(".cart").hide();
	}
}

//在购物车页面，点击“-减号”事件
$(document).on("click", ".item .minus", function(){
	var number = parseInt($("#"+$(this).attr("name")).text())-1;
	console.log("number:"+number);
	if(number >= 1){
		$("#"+$(this).attr("name")).text(number);
	}
	else 
		return ;
	var id = $(this).attr("name").split("numberofid")[1];
	console.log("id:"+id);
	var current_price = parseFloat($("#tuan-all").text());
	console.log("current_price:"+current_price);
	$("#tuan-all").text(current_price-parseFloat($("#priceofid"+id).val()));
	//$("#tuan-all").text(number*parseInt($("#priceofid"+id).val()));
});

//在购物车页面，点击“+加号”事件
$(document).on("click", ".item .plus", function(){
	var number = parseInt($("#"+$(this).attr("name")).text())+1;
	if(number >= 1){
		$("#"+$(this).attr("name")).text(number);
	}
	else
		return ;
	var id = $(this).attr("name").split("numberofid")[1];
	var current_price = parseFloat($("#tuan-all").text());
	console.log("current_price:"+current_price);
	$("#tuan-all").text(current_price+parseFloat($("#priceofid"+id).val()));
	
});

//购物车页面，“删除”点击事件
$(document).on("click", ".item-remove", function(){
	var $self = $(this);
	var item_id	= $self.attr("id");
	var price	= $self.attr("name");
	var number = parseInt($("#numberofid"+item_id).text());
	var url = baseUrl + "student/studentAction_removeProduct.action";
	$.ajax({
		url: url,
		data:{cartId:cartId,productId:item_id},
		beforeSend:function(){
			showLoading();
		},
		success: function(data){
//			debugger;
			var data = eval("("+data+")");
			if(data.sign==1){//删除成功

				if(fruits[item_id] > 0){//之前加入购物车了
					fruits[item_id] = -1;
				}
				
				//从fruit数组中移除该商品ID
//				var k=-1;//记录移除了哪个位置的ID
//				for(var i in fruits){
//					if(fruits[i]==item_id) {
//						fruits[i]=-1;
//						k=i;
//					}
//				}
//				
//				var temp = Array();
//				for(var i in fruits){
//					if(fruits[i]>0) temp.push(fruits[i]);
//				}
//				fruits = temp;
				
				//fruits对应的数量也要相应的修改
//				if(k>0){counts[k]=-1;}
//				
//				var temp_count = Array();
//				for(var i in counts){
//					if(counts[i]>0) {
//						temp_count.push(counts[i]);
//					}
//				}
//				counts = temp_count;
				
				console.log("after delete fruits:"+fruits);
				
				$self.parent().parent().remove();
				
				var $tuanAll = $("#tuan-all");
				$tuanAll.text(parseInt($tuanAll.text())-(price*number));
				//setShadow();
				myAlert("删除成功");
			}else{//data.login == 0删除失败
				myAlert("删除失败");
			}
		},
		error: function(data){
			myAlert("删除失败");
		},
		complete:function(){
			hideLoading();
		}
	});

});

//在购物车页面，提交订单，点击事件
$(document).on("click", "#order-submit", function(){

	if(_count() == 0){
		myAlert("至少选择一样水果");
		return;
	}

	var phoneNumber = $("#cart-phone").text();
	var name = $("#cart-name").text();
	var address = $("#cart-location").text();
	if(isBlank(phoneNumber) || isBlank(name) || isBlank(address)){
		myAlert("请填写完整的配送信息!");
		return;
	}
	if((phoneNumber.length>2 && phoneNumber.length<7) || phoneNumber.length==11 ){
	}else{
		myAlert("手机号码不正确");
		return;
	}
	
	//=================随心配的商品Id和数量=====================
	var labels = $(".item[name='suixinpei'] label");
	if(labels.length==1 && $(labels[0]).text()==1){
		myAlert("随心配至少搭配成一盒");
		return;
	}
	
	var deliveryTime = $("#delivery-time").get(0).selectedIndex;
	if(deliveryTime == 0){
		myAlert("请选择配送时间");
		return;
	}
	
	//判断备注,长度不超过150字符
	var remark="";
	remark = $("#cart-remark").val();
	console.log("cart-remark:"+remark)
	console.log("remark.length"+remark.length)
	if(remark.length>150) {
		myAlert("备注长度不能超过150个字");
		return;
	}
	goTo('index5.html');
});

//在购物车页面，提交订单
function submitOrder(){
	var deliveryTime = $("#delivery-time").get(0).selectedIndex;
	var remark="";
	remark = $("#cart-remark").val();
	var url ;
	url = baseUrl+"student/studentAction_submitOrders.action";
	//url = 'cartOrder2.json';

	var labels = $(".item[name='tutetuan'] label");
	var counts = Array();
	var fruitServer = Array();//该数字只用于下单提交服务器
	for(var i = 0; i < labels.length; i++){
		var id = labels[i].id.split("numberofid")[1];
		var num = $(labels[i]).text();
		fruitServer[i] = id;
		counts[i] = num;
	}
	labels = [];
	var labels = $(".item[name='suixinpei'] label");
	var j = fruitServer.length;
	for(var i = j; i < labels.length; i++){
		var id = labels[i].id.split("numberofid")[1];
		var num = $(labels[i]).text();
		fruitServer[i] = id;
		counts[i] = num;
	}	
	
	console.log("submitOrder:"+fruitServer);
	
	if(fruitServer.length > 0 && counts.length > 0){ 
		$.ajax({
			url: url,
			type: "POST",
			data: { userId:userId,cartId:cartId,deliveryTime:deliveryTime,fruits: fruitServer,counts:counts,remark:remark},
			success: function(data){
				log = data;
				// Clear all orders
				orders = Array();
				console.log(data);
				var data = eval("("+data+")");
				orderResultSet(data);
				fruitServer = Array();
			}
		});
	}
	else{
		myAlert("请至少选择一样水果呀");
	}
}

//下单成功
function orderResultSet(data){
	var order = data.order;
	var user = data.user;
	var stute = order.orderStutes;
	if(stute==0){
		//下单成功
		$("#pageE h1").text('下单成功');//data.msg
		//alert("下单成功");
		//alert(data.msg);
		$("#report-page #time").text(order.orderDate);
		var price = 0;
		var counter = 0;
		//prices = Array();
		console.log(data);
		
		$(".report-orders").empty();
		var content = "";
		for(var i in order.purchasedgood){
			counter ++;
			content = content+ "<p>"+counter + "、"+ order.purchasedgood[i].productName +"(" +
				order.purchasedgood[i].price +"元/"+order.purchasedgood[i].standard+")&nbsp;&nbsp;数量："+order.purchasedgood[i].count+"</p>";
			//prices.push(parseFloat(order.purchasedgood[i].price));
			//price += parseFloat(order.purchasedgood[i].price);

		}
		
		if(order.sxp.length>0){
			content = content+ "<p>随心配</P>";
			counter = 0;
			for(var i in order.sxp){
				counter ++;
				content = content+ "<p>"+counter + "、"+ order.sxp[i].productName +"(" +
					order.sxp[i].price +"元/"+order.sxp[i].standard+")&nbsp;&nbsp;数量："+order.sxp[i].count+"</p>";
			}	
		}
		
		content = content+ "备注："+checkRemark(order.remark);
		$("#report-page .report-orders").append(content);
		//prices.sort(function(x,y){return parseFloat(y)-parseFloat(x);}); 
		//console.log(prices.length/3);

		//	var count = data.count;
			var total =  order.totalMoney;

			$("#report-page #price").text(total);
			$("#report-page #recieved-price").text(total);
			
			//配送信息
			$("#order-name").text(user.name);
			$("#order-phone").text(user.phoneNumber);
			$("#order-location").text(user.address);
			
			//配送时间
			var deliveryTime = "";
			switch(order.deliveryTime){
			case "1":deliveryTime="19-20点"; break;
			case "2":deliveryTime="20-21点"; break;
			case "3":deliveryTime="22-23点"; break;
			case "4":deliveryTime="明天19-20点"; break;
			case "5":deliveryTime="明天20-21点"; break;
			case "6":deliveryTime="明天22-23点"; break;			
			default:deliveryTime="没有选择配送时间";
			}
			$("#order-deliveryTime").text(deliveryTime);
		$("#report-page-fail").hide();
		$("#report-page").show();
		
		//购物车清零
		fruits = Array();
		cartId = 0;
		$("#in-tuan-items div").remove();
		$("#amount_2").hide();
		$(".cart").hide();
		//setShadow();
		//配送时间重置
		var myselect = $("#delivery-time");
		myselect[0].selectedIndex = 0;
		myselect.selectmenu('refresh');
		//清除备注
		var $cartRemark = $("#cart-remark");
		$cartRemark.val("");
		$cartRemark.hide();
	}else if(stute==-1){
		//下单失败
		$("#pageE h1").text('下单失败');//data.msg
		$("#report-page").hide();
		$("#report-page-fail").show();
	}else{
		//订单的的其他的状态
	}

}

//检验备注是否为空
function checkRemark(remark){
	 if(isBlank(remark)){
		 return "无备注";
	 }else{
		 return remark;
	 }
}

//登陆页面 登陆
$(document).on("click", "#login-submit", function(){
	login();
});

function login(){
	var phoneNumber = $("#mytel").val();
	if((phoneNumber.length>2 && phoneNumber.length<7) || phoneNumber.length==11 ){
	}else{
		$("#loginPage #login-msg").text("手机号码不正确");
		return;
	}
	$("#loginPage #login-msg").text("");
	var url = baseUrl+"login/loginAction_login.action";
	$.ajax({
		url: url,
		type: 'POST',
		async: false,//同步请求
		data:{phoneNumber:phoneNumber},
		beforeSend:function(){
			$("#login-submit").addClass("ui-disabled");
		},
		success: function(data){
			var data = eval("("+data+")");
			console.log(data)
			if(data.login==0){//登陆成功
				userId = data.userId;
				userStatus = 1;
				$("#loginPage #login-msg").text('');
				
				if(!isBlank(whichPageAfterLogin)){
					goTo(whichPageAfterLogin);
				}else{
					goTo('cart.html');
				}
			}else{//data.login == 1登陆失败
				userStatus = 0;
				$("#loginPage #login-msg").text(data.msg);
			}
		},
		error: function(data){
			$("#loginPage #login-msg").text('登陆失败');
		},
		complete:function(){
			$("#login-submit").removeClass("ui-disabled");
		}
	});
}

//注册页面 注册
$(document).on("click", "#register-submit", function(){
	register();
});
function register(){
	$("#registerPage #register-msg").text('');
	var phoneNumber = $("#reg-tel").val();
	var name = $("#reg-name").val();
	var address = $("#reg-address").val();
	
	if(isBlank(phoneNumber) || isBlank(name) || isBlank(address)){
		$("#registerPage #register-msg").text("请填写完整信息!");
		return;
	}
	if((phoneNumber.length>2 && phoneNumber.length<7) || phoneNumber.length==11 ){
	}else{
		$("#registerPage #register-msg").text("手机号码不正确");
		return;
	}

	$("#registerPage #register-msg").text('');
	
	var url = baseUrl+"login/loginAction_registerAccount.action";
	console.log("phoneNumber:"+phoneNumber+"name:"+name+"address:"+address);
	$.ajax({
		url: url,
		type: "POST",
		async: false,//同步请求
		data:{recipientPhone:phoneNumber,recipientName:name,recipientAddress:address},
		beforeSend:function(){
			showLoading();
			$("#register-submit").addClass("ui-disabled");
		},
		success: function(data){
			var data = eval("("+data+")");
			if(data.sign==0){//注册成功
				userId = data.userId;
				userStatus = 1;
				$("#registerPage #register-msg").text('');

				if(!isBlank(whichPageAfterLogin)){
					goTo(whichPageAfterLogin);
				}else{
					goTo('cart.html');
				}

			}else{//data.sign == 1注册失败
				userStatus = 0;
				$("#registerPage #register-msg").text(data.msg);
			}
		},
		error: function(data){
			$("#registerPage #login-msg").text('注册失败');
		},
		complete:function(){
			hideLoading();
			$("#register-submit").removeClass("ui-disabled");
		}
	});
}
//============================详情页面=============================================
//在详情页面，“放入购物车”按钮点击事件
$(document).on("click","#cart",function(){
	var id = $("#detail-item-id").val();
	fruits[id] = id;
	var count = _count();
	$(".cart #number").text(count);
	if(count > 0){
		$(".cart").show();
	}
	else {
		$(".cart").hide();
	}
	//setShadow();
});

$(document).on("click", "#order", function(){
	$(".cart").hide();
	var id = $("#detail-item-id").val();
	fruits[id] = id;
	//userStatus = 1;
	if(userStatus == 1){
		goTo('cart.html');
	}else {
		goTo('login.html');
	}
});

//===========================我的历史订单==============================================
//查看我的历史订单
function getHistoryOrder(){
	if(userStatus == 0 || isBlank(userId)){
		myAlert("请先登录");
		goBack();
	}else{
	//var url = "history_order.json";
	var url = baseUrl+"student/studentAction_checkHistoyOrders.action";
	$.ajax({
		url: url,
		data:{userId:userId,orderstatus:0},
		beforeSend:function(){
			showLoading();
		},
		success: function(data){
			$("#mylist-page").empty();
			var data = eval("("+data+")");
			console.log(data);
			var content = "";
//			console.log(data.historyOrders);
			if(isBlank(data) || isBlank(data.historyOrders)){
				$("#mylist-page").html("<div>暂无订单。请移步到<a href='index.html'>首页</a>下单吧！</div>");
			}else{
				$.each(data.historyOrders,function(index, item) {
					if(!item){return;}
					console.log(item);
					content += "<div class='tuan'>";
					content += "<span>购买商品：</span><span>"+item.allProductName+"</span><br>";
					content += "<span>订单金额：</span><span>"+item.productTotalPrice+"元</span><br>";
					content += "<span>下单时间：</span><span>"+item.orderDate+"</span><br>";
					content += "<span>订单签收：</span><span>"+item.recipientName+"</span><br>";
					content += "<span>签收地址：</span><span>"+item.address+"</span><br>";
					content += "<span>订单备注：</span><span>"+checkRemark(item.remark)+"</span><br>";
					content += "<span>订单状态：</span><span style='color:green'>"+orderStatus(item.orderStatus)+"</span><br>";
					content += "<span id='"+item.cartId+"' data-role='button' class='btn-success ui-btn ui-btn-corner-all' onclick='getOrderDetail(id)'>查看订单详情</span>";
					content += "<div class='border'></div></div>";
				});
				
				$("#mylist-page").append(content);
			}
		},
		error: function(data){
			myAlert("查看订单历史失败");
		},
		complete:function(){
			hideLoading();
		}
	});
	}
}

function orderStatus(num){
	var status = "";
	switch(num){
	case -1 : status = "错误"; break;
	case 0 : status = "下单成功"; break;
	case 1 : status = "正在鲜切"; break;
	case 2 : status = "正在配送"; break;
	case 3 : status = "配送完成"; break;
	case 4 : status = "已结单"; break;
	default: status = "暂无";
	}
	return status;
}

//根据cartId查看订单详情
function getOrderDetail(id){
	if(!isBlank(id)){
		//alert(id)
		//var url = "history_order_detail.json";
		var url = baseUrl+"student/studentAction_checkProduct.action";
		$.ajax({
			url: url,
			data:{cartId:id},
			beforeSend:function(){
				showLoading();
			},
			success: function(data){
				var $popList = $("#history-popup .mylist-items");
				$popList.empty();
				
				var data = eval("("+data+")");
				console.log(data);
				var content = "";
				//console.log(data.productList);
				if(isBlank(data) ){
					$popList.html("<div>找不到订单详情哇。。。</div>");

				}else{
					$.each(data.productList,function(index, item) {
						if(!item){return;}
						console.log(item);
						content += "<div class='tuan'>";
						content += "<span>名称：</span><span>"+item.productName+"</span><br>";
						content += "<span>规格：</span><span>"+item.standard+"</span><br>";
						content += "<span>数量：</span><span>"+item.count+"</span><br>";
						content += "<span>小计：</span><span style='color:green'>"+item.totalPrice+"</span><br>";
						//content += "<span>时间：</span><span>"+item.orderDate+"</span><br>";
						content += "<div class='border'></div></div>";
					});
					
					$popList.append(content);
				}
			},
			error: function(data){
				myAlert("查看订单详情失败");
			},
			complete:function(){
				hideLoading();
				$("#history-popup").popup("open");
			}
		});

		//goTo("index7.html");
	}else{
		
	}
}

//在4个列表页面，点击右上角“我”查看历史订单
function goToIndex6(){
	if(userStatus == 0 || isBlank(userId)){
		myAlert("请先登录");
		whichPageAfterLogin = "index6.html";
		goTo("login.html");
	}else{
		goTo("index6.html")
	}
}